<template>
  <div class="patient-control-container" style="height: 100%; width: 100%; margin: 0; padding: 0;">
    <!-- 查询条件表单 -->
    <el-form :inline="true" :model="queryForm" class="demo-form">
      <el-form-item label="性别">
        <el-select v-model="queryForm.gender" placeholder="请选择性别" clearable style="width: 100px;">
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
          <el-option label="全部" value="全部"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="年龄">
        <el-input
            v-model.number="queryForm.startAge"
            placeholder="起始年龄"
            style="width: 100px;"
            @blur="validateAgeRange"
        >
          <template #append>至</template>
        </el-input>
        <el-input
            v-model.number="queryForm.endAge"
            placeholder="结束年龄"
            style="width: 50px;"
            @blur="validateAgeRange"
        ></el-input>
      </el-form-item>

      <el-form-item label="科室" v-if="localAuthority === '超级用户'">
        <el-select v-model="queryForm.disease" placeholder="请选择科室" clearable style="width: 150px;">
          <el-option label="甲状腺疾病" value="甲状腺疾病"></el-option>
          <el-option label="全部" value="全部"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="注册">
        <el-select v-model="queryForm.isRegister" placeholder="请选择注册情况" clearable style="width: 100px;">
          <el-option label="已注册" value="已注册"></el-option>
          <el-option label="未注册" value="未注册"></el-option>
          <el-option label="全部" value="全部"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button type="primary" @click="showAddDialog = true" class="add-button ml-2">
          <i class="el-icon-plus"></i> 增加住院号
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 表格标题和统计信息 -->
    <div class="table-header">
      <h3 class="table-title">住院号信息列表</h3>
      <div class="table-info">
        <span class="total-count">共 {{ total }} 条记录</span>
      </div>
    </div>

    <!-- 表格部分 -->
    <el-table
        :data="patientInfo"
        border
        style="width: 100%; height: calc(100% - 180px); margin: 0;"
        :row-style="{ height: '48px' }"
        :cell-style="{ padding: '0' }"
    >
      <el-table-column prop="hospitalNumber" label="住院号" min-width="100px"></el-table-column>
      <el-table-column prop="idCard" label="身份证号" min-width="180px"></el-table-column>
      <el-table-column prop="gender" label="性别" min-width="60px"></el-table-column>
      <el-table-column prop="age" label="年龄" min-width="60px"></el-table-column>
      <el-table-column prop="disease" label="疾病类型" min-width="120px"></el-table-column>
      <el-table-column prop="isRegister" label="注册情况" min-width="100px"></el-table-column>
      <el-table-column fixed="right" label="操作" min-width="120px">
        <template v-slot:default="scope">
          <el-button type="text" size="small" @click="handleDelete(scope.row)">
            <i class="el-icon-delete"></i> 删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页部分 -->
    <el-row style="margin-top: 10px; width: 100%;">
      <el-col :span="24">
        <el-pagination
            @size-change="sizeChange"
            @current-change="currentChange"
            :current-page="page"
            :page-size="size"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
        ></el-pagination>
      </el-col>
    </el-row>

    <!-- 增加住院号弹窗 -->
    <el-dialog title="添加住院号" v-model="showAddDialog" width="25%">
      <div style="display: flex; justify-content: center; flex-direction: column; padding: 20px;">
        <!-- 住院号输入框，带提示按钮 -->
        <div style="margin-bottom: 15px; display: flex; align-items: center;">
          <span style="display: inline-block; width: 80px; text-align: right; margin-right: 10px;">住院号</span>
          <el-input
              v-model="addHospitalNumber"
              placeholder="请输入住院号"
              style="width: 100%;"
          ></el-input>
          <el-tooltip content="若无法查询到用户住院号，可输入数字0，系统会自动给用户生成一个6位数字的住院号" placement="right">
            <el-button type="text" style="margin-left: 10px;">
              <el-icon><QuestionFilled /></el-icon>
            </el-button>
          </el-tooltip>
        </div>

        <!-- 身份证号输入框 -->
        <div style="margin-bottom: 15px; display: flex; align-items: center;">
          <span style="display: inline-block; width: 80px; text-align: right; margin-right: 10px;">身份证号</span>
          <el-input
              v-model="addIdCard"
              placeholder="请输入身份证号"
              style="width: 100%;"
          ></el-input>
        </div>

        <!-- 病患科室选择框 -->
        <div style="display: flex; align-items: center;">
          <span style="display: inline-block; width: 80px; text-align: right; margin-right: 10px;">病患科室</span>
          <el-select
              v-model="addAuthority"
              placeholder="请选择科室"
              style="width: 100%;"
          >
            <el-option label="甲状腺疾病" value="甲状腺疾病"></el-option>
          </el-select>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="handleAdd">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref } from 'vue';
import { apiClient } from '../api/apiClient';
import { ElMessage, ElMessageBox, ElTooltip } from 'element-plus';
import { QuestionFilled } from '@element-plus/icons-vue'

// 身份证号校验函数
const validateIdCard = (idCard) => {
  if (idCard === '') {
    return false
  }
  const idCardReg = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/;

  if (!idCardReg.test(idCard)) {
    return false
  }

  // 校验码计算（GB 11643-1999标准）
  const weight = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; // 加权因子
  const checkCode = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']; // 校验码对照表
  let sum = 0;

  // 计算前17位加权和
  for (let i = 0; i < 17; i++) {
    sum += parseInt(idCard.charAt(i)) * weight[i];
  }

  const mod = sum % 11; // 取模
  const lastChar = idCard.charAt(17).toUpperCase(); // 最后一位（转大写）

  // 校验码比对
  if (checkCode[mod] !== lastChar) {
    return false
  }

  // 验证通过
  return true
};

export default {
  components: {
    ElTooltip
  },
  setup() {
    // 查询条件
    const queryForm = ref({
      gender: '全部',
      startAge: 0,
      endAge: 120,
      disease: '全部',
      isRegister: '全部'
    });

    // 增加住院号相关
    const showAddDialog = ref(false);
    const addHospitalNumber = ref('');
    const addIdCard = ref('');
    const addAuthority = ref('甲状腺疾病');
    const localAuthority = ref(localStorage.getItem('authority'));

    // 表格数据相关
    const page = ref(1);
    const size = ref(10);
    const total = ref(0);
    const allPatientInfo = ref([]);
    const patientInfo = ref([]);

    // 验证年龄范围
    const validateAgeRange = () => {
      const { startAge, endAge } = queryForm.value;

      // 验证起始年龄
      if (startAge !== '' && (isNaN(Number(startAge)) || Number(startAge) < 0 || Number(startAge) > 120)) {
        ElMessage.error('请输入0-120之间的合法年龄数字');
        return false;
      }

      // 验证结束年龄
      if (endAge !== '' && (isNaN(Number(endAge)) || Number(endAge) < 0 || Number(endAge) > 120)) {
        ElMessage.error('请输入0-120之间的合法年龄数字');
        return false;
      }

      // 验证年龄范围
      if (startAge !== '' && endAge !== '' && Number(endAge) < Number(startAge)) {
        ElMessage.error('结束年龄必须大于等于起始年龄');
        return false;
      }

      return true;
    };

    const handleQuery = async () => {
      if (!validateAgeRange()) {
        return; // 如果年龄验证不通过，直接返回，不执行查询
      }

      try {
        //const diseaseParam = localAuthority.value === '超级用户1'
        //    ? queryForm.value.disease
        //    : localAuthority.value;
        const diseaseParam = '甲状腺疾病';
        const response = await apiClient.get('/patient/selectPatientInfo', {
          params: {
            gender: queryForm.value.gender,
            startAge: Number(queryForm.value.startAge),
            endAge: Number(queryForm.value.endAge),
            disease: diseaseParam,
            isRegister: queryForm.value.isRegister
          }
        });

        if (response.data.code === 1) {
          allPatientInfo.value = response.data.data;
          total.value = allPatientInfo.value.length;
          getTableData();
        } else {
          console.error('Failed to fetch patient info:', response.data.msg);
          ElMessage.error('获取数据失败，请稍后重试');
        }
      } catch (error) {
        console.error('Failed to fetch patient info:', error);
        ElMessage.error('网络请求失败，请稍后重试');
      }
    };

    const handleAdd = async () => {
      // 表单验证
      if (!addHospitalNumber.value) {
        ElMessage.error('请输入住院号');
        return;
      }

      // 住院号验证：必须是0或8位数字
      if (addHospitalNumber.value !== '0' && !/^\d{8}$/.test(addHospitalNumber.value)) {
        ElMessage.error('请输入正确的住院号');
        return;
      }

      if (!addIdCard.value) {
        ElMessage.error('请输入身份证号');
        return;
      }

      if (!validateIdCard(addIdCard.value)) {
        ElMessage.error('请输入正确的身份证号');
        return;
      }

      try {
        await ElMessageBox.confirm(
            `确定添加住院号: ${addHospitalNumber.value} 吗？`,
            '确认添加',
            {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning'
            }
        );

        const authorityToSend = localAuthority.value === '超级用户1' ? addAuthority.value : localAuthority.value;
        const formData = new FormData();
        formData.append('hospitalNumber', addHospitalNumber.value);
        formData.append('authority', authorityToSend);
        formData.append('idCard', addIdCard.value);
        formData.append('limRevisitTime', '-10');  // 固定回访周期为-10

        const response = await apiClient.post('/patient/add', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        if (response.data.code === 1) {
          ElMessage.success(`成功添加住院号: ${addHospitalNumber.value}`);
          // 清空表单
          addHospitalNumber.value = '';
          addIdCard.value = '';
          showAddDialog.value = false;
          handleQuery(); // 添加成功后刷新数据
        } else {
          ElMessage.error(`添加失败: ${response.data.msg || '未知错误'}`);
        }
      } catch (error) {
        if (error === 'cancel') return;
        console.error('添加住院号失败:', error);
        ElMessage.error('网络请求失败，请稍后重试');
      }
    };

    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm(
            `确定删除住院号: ${row.hospitalNumber} 吗？`,
            '确认删除',
            {
              confirmButtonText: '删除',
              cancelButtonText: '取消',
              type: 'error'
            }
        );

        const response = await apiClient.delete(`/patient/delete?hospitalNumber=${row.hospitalNumber}`);

        if (response.data.code === 1) {
          ElMessage.success(`成功删除住院号: ${row.hospitalNumber}`);
          handleQuery(); // 删除成功后刷新数据
        } else {
          ElMessage.error(`删除失败: ${response.data.msg || '未知错误'}`);
        }
      } catch (error) {
        if (error === 'cancel') return;
        console.error('删除住院号失败:', error);
        ElMessage.error('网络请求失败，请稍后重试');
      }
    };

    const getTableData = () => {
      patientInfo.value = allPatientInfo.value.slice((page.value - 1) * size.value, page.value * size.value);
    };

    const sizeChange = (newSize) => {
      size.value = newSize;
      getTableData();
    };

    const currentChange = (newPage) => {
      page.value = newPage;
      getTableData();
    };

    return {
      queryForm,
      showAddDialog,
      addHospitalNumber,
      addIdCard,
      addAuthority,
      localAuthority,
      page,
      size,
      total,
      patientInfo,
      validateAgeRange,
      handleQuery,
      handleAdd,
      handleDelete,
      getTableData,
      sizeChange,
      currentChange
    };
  }
};
</script>

<style scoped>
.patient-control-container {
  box-sizing: border-box;
  margin: 0;
  padding: 20px;
}

.demo-form {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 15px;
  width: 100%; /* 确保表单占满宽度 */
  box-sizing: border-box;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  width: 100%; /* 确保标题栏占满宽度 */
  box-sizing: border-box;
}

.table-title {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
  margin: 0;
}

.table-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.total-count {
  color: #606266;
  font-size: 14px;
}

.add-button {
  display: flex;
  align-items: center;
}

.ml-2 {
  margin-left: 10px;
}
</style>